package deviceImpl;

import server.DeviceImpl;
import server.Server;
import util.ServerUtil;

public class BasicDeviceImpl implements DeviceImpl {

    public static void main(String[] args) {
        new BasicDeviceImpl();
    }

    private final int port = 3500;

    private final Server server;

    public BasicDeviceImpl() {
        server = new Server(this);
        server.start(port);
    }

    public String getFullId(String id) {
        return "C:/TCC/functions_Basic/" + id + ".xml";
    }

    public String getFunctions() {
        return ServerUtil.getContentFile(getFullId("functions"));
    }

    public String getForm(String functionId) {
        if (functionId.equals("FNC1")) {
            return ServerUtil.getContentFile(getFullId("FormShutDown"));
        }
        if (functionId.equals("FNC2")) {
            return ServerUtil.getContentFile(getFullId("FormAlert"));
        }
        return null;
    }

    public String executeCommand(String command) {
        if (command.equals("getFunctions")) {
            return getFunctions();
        }
        if (command.startsWith("getForm")) {
            //o formato deve ser getForm:functionID
            final String functionID = command.split(":")[1];
            return getForm(functionID);
        }
        if (command.startsWith("execFuntion")) {
            //o formato deve ser execFuntion:formID:action
            String[] split = command.split(":");
            final String functionID = command.split(":")[1];
            StringBuilder sb = new StringBuilder();
            sb.append(executeFunction(split[1], split[2]));
            return sb.toString();
        }

        return "Command not found";
    }

    public String executeFunction(String formID, String action) {
        if (formID.equals("FormFc1")) {
            if (action.equals("Bt1")) {
                shutdown();
                return "OK";
            }
            if (action.equals("Bt2")) {
                hibernate();
                return "OK";
            }
        }
        if (formID.equals("FormFc2")) {
            if (action.equals("Bt1")) {
                alert("Rango na mesa");
                return "OK";
            }
            if (action.equals("Bt2")) {
                alert("Telefone");
                return "OK";
            }
            if (action.equals("Bt3")) {
                alert("Trovoada");
                return "OK";
            }
        }

        return "FAIL";
    }

    private void alert(String message) {
        System.out.println("!!!!!ALERTA!!!!!");
        System.out.println(message);
    }

    private void hibernate() {
        System.out.println("Hibenando");
    }

    private void shutdown() {
        System.out.println("Desligando");
    }

}
